package com.woorigil.android.sample.activity.intro.command;

import com.woorigil.android.sample.AppContext;
import com.woorigil.android.sample.Constants;
import com.woorigil.android.sample.domain.BeanFactory;
import com.woorigil.android.sample.domain.app.AppInfomationDao;
import com.woorigil.android.sample.domain.app.AppInformation;
import com.woorigil.android.sample.support.CategoryUtils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class AppInformationSettingCommand implements Command {
	
	@Override
	public void execute(Context context) {
		AppInformation appInformation = BeanFactory.getBean(context.getApplicationContext(), AppInfomationDao.class).initializeApp();
		initPreferences(context, appInformation);
		initAppContext(context, appInformation);
	}
	
	public void initPreferences(Context context, AppInformation appInformation) {
		SharedPreferences preferences = context.getSharedPreferences(Constants.PREFERENCE_NAME, Activity.MODE_PRIVATE);
		Editor editor = preferences.edit();
		editor.putString(Constants.KEY_APP_VERSION, appInformation.getAppVersion());
		editor.putInt(Constants.KEY_PRODUCT_TOTAL_COUNT, appInformation.getDealTotalCount());
		editor.putInt(Constants.KEY_PRODUCT_LIMIT_COUNT, appInformation.getDealListLimitCount());
		editor.putLong(Constants.KEY_LAST_UPDATE_TIME, appInformation.getLastUpdatedTime());
		editor.putString(Constants.KEY_CATEGORY_JSON, appInformation.getCategoryJson());
		editor.commit();
	}
	
	public void initAppContext(Context context, AppInformation appInformation) {
		AppContext.setAppVersion(appInformation.getAppVersion());
		AppContext.setDealTotalCount(appInformation.getDealTotalCount());
		AppContext.setDealListLimitCount(appInformation.getDealListLimitCount());
		AppContext.setLastUpdatedTime(appInformation.getLastUpdatedTime());
		
		CategoryUtils.initCategory(appInformation.getCategoryJson());
		AppContext.setMainCategories(appInformation.getMainCategories());
		AppContext.setSubCategories(appInformation.getSubCategories());
	}
}
